#!/usr/bin/env python3
"""
Setup verification script for VectorDB microservice.

This script checks if all dependencies are installed and the service is ready to run.
"""

import sys
import subprocess
import importlib
import httpx
import asyncio
from pathlib import Path


def check_python_version():
    """Check Python version."""
    print("🔍 Checking Python version...")
    version = sys.version_info
    if version >= (3, 8):
        print(f"   ✅ Python {version.major}.{version.minor}.{version.micro} - OK")
        return True
    else:
        print(f"   ❌ Python {version.major}.{version.minor}.{version.micro} - Requires Python 3.8+")
        return False


def check_dependencies():
    """Check if required dependencies are installed."""
    print("🔍 Checking dependencies...")

    required_packages = [
        "fastapi", "uvicorn", "lancedb", "httpx", "websockets",
        "pyarrow", "numpy", "pydantic", "yaml", "dotenv"
    ]

    missing_packages = []

    for package in required_packages:
        try:
            importlib.import_module(package)
            print(f"   ✅ {package}")
        except ImportError:
            print(f"   ❌ {package} - Not installed")
            missing_packages.append(package)

    if missing_packages:
        print(f"\n   📦 Missing packages: {', '.join(missing_packages)}")
        print("   💡 Install with: pip install -r requirements.txt")
        return False

    print("   ✅ All required dependencies are installed")
    return True


def check_configuration():
    """Check configuration files."""
    print("🔍 Checking configuration...")

    config_files = [
        "config.yaml",
        ".env",
        "requirements.txt"
    ]

    missing_files = []

    for file in config_files:
        if Path(file).exists():
            print(f"   ✅ {file}")
        else:
            print(f"   ❌ {file} - Not found")
            missing_files.append(file)

    if missing_files:
        print(f"\n   📁 Missing files: {', '.join(missing_files)}")
        return False

    print("   ✅ All configuration files are present")
    return True


def check_directories():
    """Check required directories."""
    print("🔍 Checking directories...")

    directories = [
        "core",
        "api",
        "examples",
        "tests"
    ]

    missing_dirs = []

    for directory in directories:
        if Path(directory).exists() and Path(directory).is_dir():
            print(f"   ✅ {directory}/")
        else:
            print(f"   ❌ {directory}/ - Not found")
            missing_dirs.append(directory)

    if missing_dirs:
        print(f"\n   📂 Missing directories: {', '.join(missing_dirs)}")
        return False

    print("   ✅ All required directories are present")
    return True


async def check_ollama_connection():
    """Check Ollama connection."""
    print("🔍 Checking Ollama connection...")

    try:
        async with httpx.AsyncClient(timeout=5.0) as client:
            response = await client.get("http://localhost:11434/api/tags")

            if response.status_code == 200:
                data = response.json()
                models = data.get("models", [])

                print(f"   ✅ Ollama is running")
                print(f"   📊 Available models: {len(models)}")

                # Check for qwen3-embedding model
                model_names = [m.get("name", "") for m in models]
                if "qwen3-embedding:0.6b" in model_names:
                    print(f"   ✅ qwen3-embedding:0.6b model is available")
                else:
                    print(f"   ⚠️  qwen3-embedding:0.6b model not found")
                    print(f"   💡 Install with: ollama pull qwen3-embedding:0.6b")

                return True
            else:
                print(f"   ❌ Ollama returned status {response.status_code}")
                return False

    except httpx.ConnectError:
        print("   ❌ Cannot connect to Ollama at localhost:11434")
        print("   💡 Start Ollama with: ollama serve")
        return False
    except Exception as e:
        print(f"   ❌ Error checking Ollama: {e}")
        return False


def check_python_imports():
    """Check if Python modules can be imported."""
    print("🔍 Checking Python imports...")

    modules_to_check = [
        ("core.config", "Configuration management"),
        ("core.database", "Database operations"),
        ("core.embedding", "Embedding services"),
        ("api.models", "API models"),
        ("api.routes", "API routes"),
        ("main", "Main application")
    ]

    # Add parent directory to path for imports
    sys.path.insert(0, str(Path(__file__).parent))

    failed_imports = []

    for module_name, description in modules_to_check:
        try:
            importlib.import_module(module_name)
            print(f"   ✅ {module_name} - {description}")
        except ImportError as e:
            print(f"   ❌ {module_name} - {description}")
            print(f"      Error: {e}")
            failed_imports.append(module_name)

    if failed_imports:
        return False

    print("   ✅ All modules can be imported successfully")
    return True


def main():
    """Main verification function."""
    print("VectorDB Microservice - Setup Verification")
    print("=" * 50)
    print()

    all_checks_passed = True

    # Run all checks
    checks = [
        ("Python Version", check_python_version),
        ("Dependencies", check_dependencies),
        ("Configuration", check_configuration),
        ("Directories", check_directories),
        ("Python Imports", check_python_imports),
    ]

    for check_name, check_func in checks:
        try:
            result = check_func()
            if not result:
                all_checks_passed = False
        except Exception as e:
            print(f"   ❌ {check_name} - Error: {e}")
            all_checks_passed = False
        print()

    # Check Ollama (optional but recommended)
    print("🔍 Checking Ollama (optional)...")
    try:
        ollama_result = asyncio.run(check_ollama_connection())
        if not ollama_result:
            print("   ⚠️  Ollama check failed, but service can still run with other providers")
    except Exception as e:
        print(f"   ⚠️  Could not check Ollama: {e}")
    print()

    # Final summary
    print("=" * 50)
    if all_checks_passed:
        print("🎉 All essential checks passed!")
        print()
        print("🚀 You can now start the VectorDB microservice:")
        print("   python start.py dev")
        print()
        print("📚 Or run the examples:")
        print("   python examples/basic_usage.py")
        print("   python examples/rag_integration.py")
        print("   python examples/websocket_example.py")
    else:
        print("❌ Some checks failed. Please fix the issues above before starting the service.")
        print()
        print("💡 Common fixes:")
        print("   - Install missing dependencies: pip install -r requirements.txt")
        print("   - Start Ollama: ollama serve")
        print("   - Pull embedding model: ollama pull qwen3-embedding:0.6b")
        print("   - Check configuration files are present")

    return 0 if all_checks_passed else 1


if __name__ == "__main__":
    sys.exit(main())